package domain.DAO;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import domain.Contact;
import domain.ContactGroup;
import domain.interfaces.IDAOContactGroup;

import util.HibernateUtil;

public class DAOContactGroup extends DAOCrud<ContactGroup> implements
		IDAOContactGroup {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public DAOContactGroup() {
		super(ContactGroup.class);
	}

	@Override
	public void delete(ContactGroup entity) {
		ContactGroup newCG = hibernateTemplate.merge(entity);
		Set<Contact> sc = new HashSet<Contact>(newCG.getListOfContacts());
		for (Contact c : sc) {
			Contact newC = hibernateTemplate.merge(c);
			newC.getBooks().remove(newCG);
			hibernateTemplate.update(newC);
		}
		hibernateTemplate.delete(newCG);
	}

	@Override
	public ContactGroup find(long id) {
		hibernateTemplate.setCacheQueries(true);
		DetachedCriteria query = DetachedCriteria.forClass(this.entityClass)
				.add(Restrictions.idEq(id))
				.setFetchMode("listOfContacts", FetchMode.JOIN);
		hibernateTemplate.setCacheQueries(false);
		return (ContactGroup) hibernateTemplate.findByCriteria(query).get(0);
	}

	public ContactGroup findByExample(ContactGroup exCG) {
		return (ContactGroup) hibernateTemplate.findByExample(exCG).get(0);
	}
	
	public ContactGroup findByNamedParam(Long value) {
		String queryString = "from ContactGroup where id = :id";
		return (ContactGroup) hibernateTemplate.findByNamedParam(queryString, "id", value).get(0);
	}
	
	@SuppressWarnings("unchecked")
	public Set<ContactGroup> findAll() {
		hibernateTemplate.setCacheQueries(true);
		DetachedCriteria query = DetachedCriteria.forClass(this.entityClass)
				.setFetchMode("listOfContacts", FetchMode.JOIN)
				.addOrder(Order.asc("id"));
		hibernateTemplate.setCacheQueries(false);
		List<ContactGroup> all = hibernateTemplate.findByCriteria(query);
		return new HashSet<ContactGroup>(all);
	}
}
